package com.chezhujie.www.controller;

import com.xy.core.utils.FileDownload;
import com.xy.core.utils.Freemarker;
import com.xy.core.utils.PathUtil;
import com.xy.user.base.controller.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;



/**
 * Created by 汤伟杰 on 2017/8/25.
 */
@Controller
@RequestMapping("/download")
public class DownloadController extends BaseController{

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @RequestMapping("/morefun/data.do")
    public void sss(HttpServletResponse response) throws Exception {
        String date = "20170825";
        Map<String, Object> mapobj =new HashMap<>();
//        jdbcTemplate.update("use information_schema");
        List<Map<String, Object>> listmap = jdbcTemplate.queryForList("select * from information_schema.TABLES where TABLE_SCHEMA='morefun' order by TABLE_NAME ASC");
        List<Map<String, Object>> listmap2 = jdbcTemplate.queryForList("select * from information_schema.columns where table_schema ='morefun'  order by TABLE_NAME ASC,ORDINAL_POSITION DESC");
        for (int i = 0; i < listmap.size(); i++) {
            for (int i1 = listmap2.size() - 1; i1 >= 0; i1--) {
                if(((String)listmap.get(i).get("TABLE_NAME")).equals((String)listmap2.get(i1).get("TABLE_NAME"))){
                    List<Map<String,Object>> list = (List<Map<String,Object>>)listmap.get(i).get("list");
                    if(list==null){
                        list = new ArrayList<>();
                    }
                    list.add(listmap2.get(i1));
                    listmap.get(i).put("list", list);
                    listmap2.remove(i1);
                }
            }
        }
        mapobj.put("listmap", listmap);

        downloadTemplate(mapobj,"morefun.ftl","MOREFUN数字字典",date,".doc",response);
    }
    public void downloadTemplate(Map<String,Object> root, String ftlName, String docName, String yearmonth, String filetype, HttpServletResponse resp) throws Exception {
//		DelAllFile.delFolder(PathUtil.getClasspath()+"admin/ftl"); //生成代码前,先清空之前生成的代码
        String name = ftlName.substring(0,ftlName.lastIndexOf("."));
        /*生成 月结 列表*/
        Freemarker.printFile("resources/templete/"+ftlName, root, "download/"+name+"/"+yearmonth+filetype);
		/*下载代码*/
        FileDownload.fileDownload(resp, PathUtil.getWebpath()+"download/"+name+"/"+ yearmonth +filetype, docName+"_"+yearmonth+filetype);

    }
}
